#    Copyright 2012 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPWeb.
#    COOPWeb is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPWeb is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPWeb.  If not, see <http://www.gnu.org/licenses/>.

#************************BEGIN Add Include Files to Path************************
import sys
NeededPaths=['/opt/coopweb/djangoproject/include', '/opt/coopweb/djangoproject']
for path in NeededPaths:
    if(not path in sys.path):
        sys.path.append(path)
#************************END   Add Include Files to Path************************
import os, datetime
from django.contrib.gis.db import models
from django.http import HttpResponse
from django.contrib import admin
from django.template import Context, loader
from models import *
from django import forms


def CreateBackup(request):
    """Creates a Backup of COOPWeb suitable for FTP"""
    COOPWebBackupLocation='/opt/coopwebbackup/'

    os.system("rm -rf " + COOPWebBackupLocation + '/*') 
    BackupName='COOPWebBackup_' #+ str(datetime.datetime.today())[:10].replace('-','_')
    BackupFolderName=COOPWebBackupLocation + 'TemporaryBackupFolder/'
    os.system("mkdir " + BackupFolderName)
    os.system("chmod -R 777 " + BackupFolderName) 
    os.system("pg_dump coopweb > " + BackupFolderName + "coopweb.sql")
    os.system("cp -R /opt " + BackupFolderName)
    os.system("cp -R /etc/apache2 " + BackupFolderName)
    os.system("cp -R /etc/postgresql " + BackupFolderName)
    os.system("cp -R /scripts " + BackupFolderName)
    os.system("chmod -R 777 " + BackupFolderName) 
    os.system("tar cvzf " + COOPWebBackupLocation + BackupName + '.tgz ' + BackupFolderName)
    os.system("chmod -R 777 " + COOPWebBackupLocation + BackupName + '.tgz ')
    os.system("rm -R " + BackupFolderName)
    #End Backup Creation
    t = loader.get_template('/opt/coopweb/djangoproject/templates/mainmenu.html')
    c = Context({})
    return HttpResponse(t.render(c))
